/*
 * @Author: wuyuxin
 * @Date: 2022-01-11 16:38:14
 * @LastEditors: wuyuxin
 * @LastEditTime: 2022-01-11 18:02:25
 * @Description: 
 */

import { LOADING_SOURCE_CODE, NOT_BOOTSTRAPPED, NOT_LOADED } from "../applications/app.helpers";

function flattenFnArray(fns) { // 将函数通过then链连接起来
  fns = Array.isArray(fns) ? fns : [fns];
  // 通过promise链来链式调用
  // Promise.resolve().then(() => fn1(props)).then(() => fn2(props))
  return function(props) {
      return fns.reduce((p, fn) => p.then(() => fn(props)), Promise.resolve());
  }
}

export async function toLoadPromise(app) {
  if(app.loadPromise){
    return app.loadPromise; // 缓存机制
  }
  if (app.status !== NOT_LOADED) {
    return app;
  }
  app.status = LOADING_SOURCE_CODE;
  return (app.loadPromise = Promise.resolve().then(async ()=>{
    let { bootstrap, mount, unmount } = await app.loadApp(app.customProps);

    app.status = NOT_BOOTSTRAPPED;
    app.bootstrap = flattenFnArray(bootstrap);
    app.mount = flattenFnArray(mount);
    app.unmount = flattenFnArray(unmount);
    delete app.loadPromise;
    return app;
  }));
}
